﻿using Devonline.AspNetCore;
using Devonline.Communication.Messages;
using Devonline.Core;
using Devonline.Entity;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Serilog;

var builder = WebApplication.CreateBuilder(args);
builder.Host.UseSerilog((context, logger) => logger.ReadFrom.Configuration(context.Configuration));
builder.AddCommunicator();

var services = builder.Services;
services.AddLogging();

var app = builder.Build();
await app.StartAsync();

var logger = app.Services.GetService<ILogger<Program>>();
var communicator = app.Services.GetService<IMessageCommunicator>();
if (communicator != null && logger != null)
{
    try
    {
        Message? _message = null;
        communicator.Receive += (sender, message) => _message = message;
        communicator.Connected += (sender, e) =>
        {
            logger.LogWarning("通讯器已经启动");
            logger.LogInformation("输入 {command} 退出", "exit");
            logger.LogInformation("输入 {command} 将最后一条收到的消息标记为已读", "read");
            logger.LogInformation("输入其余任意内容将视为消息内容发送给接收者");
        };

        await communicator.StartAsync();
        var input = Console.ReadLine();
        while (input != "exit")
        {
            if (!string.IsNullOrWhiteSpace(input))
            {
                switch (input)
                {
                    case "read":
                        if (_message != null)
                        {
                            await communicator.ReadAsync(_message.Id);
                            _message = null;
                        }
                        break;
                    default:
                        await communicator.SendAsync(input);
                        break;
                }
            }

            input = Console.ReadLine();
        }

        await communicator.StopAsync();
    }
    catch (Exception ex)
    {
        logger.LogError(ex, "客户端链接出错, {message}", ex.GetInnerException());
    }

    await app.StopAsync();
    logger.LogInformation("客户端退出, 消息中心连接结束!");
}